package cn.rkylin.oms.system.storage.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.system.project.vo.ProjectVO;
import cn.rkylin.oms.system.storage.dao.StorDAOImpl;
import cn.rkylin.oms.system.storage.domain.Stor;
import cn.rkylin.oms.system.storage.service.IStorService;
import cn.rkylin.oms.system.storage.vo.StorVO;

/**
 * 仓库管理
 */
@Controller
@RequestMapping("/stor")
public class StorController extends ApolloController {
    private static final Log logger = LogFactory.getLog(StorController.class);
    // 常量定义
    private static final String PAGE_SELECT_STATEMENT = "pageSelectShop"; // 分页语句Statement名称
    private static final String GOTO_STOR_LIST = "/system/organization/storage/StorList"; // 跳转到店铺列表页

    /**
     * 仓库服务层
     */
    @Autowired
    private IStorService storService;

    /**
     * 构造函数
     */
    public StorController() {

    }

    /**
     * 跳转到仓库列表
     */
    @RequestMapping(value = "/gotoStorList")
    public String gotoRoleList() {
        return GOTO_STOR_LIST;
    }

    /**
     * 方法简要描述信息.
     * <p>
     * 描述: 根据查询条件获取仓库
     * </p>
     * <p>
     * 备注: 详见顺序图<br>
     * </p>
     *
     * @param quickSearch
     * @param stor
     * @param formJson
     * @param start
     * @param length
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/storList", method = RequestMethod.GET)
    public Map<String, Object> getStorList(String quickSearch, StorVO stor, String formJson,String storType,
            @RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "10") int length)
            throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            CurrentUser currUser = WebContextFactory.getWebContext().getCurrentUser();
            // 前台搜索条件，此处只有一个角色名称
            StorVO param = new StorVO();
            param.setEntId(currUser.getCurrentProject().getEntId());
            if (quickSearch != null) {
                quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
                if (StringUtils.isNotEmpty(quickSearch)) {
                    param.setSearchCondition(quickSearch);
                }
            } else {
                if (formJson != null) {
                    // 高级查询检索条件
                    formJson = URLDecoder.decode(formJson, "UTF-8");
                    Stor storVO = JSONObject.parseObject(formJson, Stor.class);

                    if (storVO != null) {
                        if (StringUtils.isNotEmpty(storVO.getStorName())) {
                            param.setStorName(storVO.getStorName());
                        }
                        if (StringUtils.isNotEmpty(storVO.getStorCode())) {
                            param.setStorCode(storVO.getStorCode());
                        }
                    }
                }
            }
            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;
            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("validateStatus", "validate");
            replaceFieldsMap.put("status", "enable");
            // 排序语句生成
            String orderStatement = getOrderString(StorDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }
            
            if (StringUtils.isNotEmpty(storType)) {
                param.setStorType(storType);;
            }
            
            
            // 获取分页数据
            PageInfo<StorVO> storVOList = storService.findByWhere(page, length, param);
            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RECORDS_FILTERED, storVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, storVOList.getTotal());
            returnMap.put(RETURN_DATA, storVOList.getList());

        } catch (Exception ex) {
            logger.error(ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 根据当前项目，获取当前项目下的所有仓库
     * 
     * @param projectId
     *            项目id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/storageByProjectId", method = RequestMethod.GET)
    public Map<String, Object> getStorageByProjectId(String projectId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 用于返回值的json对象
            Map<String, Object> resultMap = new HashMap<String, Object>();
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            // 已经登录 && 当前用户具有项目权限
            if (currentUser == null) {
                resultMap.put(JSON_RESULT, FAILED);
                resultMap.put(JSON_MSG, "当前用户失效");
                return resultMap;
            }
            if (currentUser.getProjectMap() == null || currentUser.getProjectMap().size() <= 0) {
                resultMap.put(JSON_RESULT, FAILED);
                resultMap.put(JSON_MSG, "当前用户没有项目权限");
                return resultMap;
            }
            String entId = null;
            // 找前台选择的项目，对应的企业（这种做法是为了适应，用户对应到多个企业下的情况。）
            for (ProjectVO project : currentUser.getProjectMap().values()) {
                if (project.getPrjId().equalsIgnoreCase(projectId)) {
                    entId = project.getEntId();
                }
            }
            StorVO storVO = new StorVO();
            storVO.setEntId(entId);
            List<StorVO> list = storService.getStorByCondition(storVO);
            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, list);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    @ResponseBody
    @RequestMapping(value = "/getStorageByShopIdNoDelete", method = RequestMethod.GET)
    public Map<String, Object> getStorageByShopIdNoDelete(String shopId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 用于返回值的json对象
            Map<String, Object> resultMap = new HashMap<String, Object>();
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null) {
                resultMap.put(JSON_RESULT, FAILED);
                resultMap.put(JSON_MSG, "当前用户失效");
                return resultMap;
            }

            List<StorVO> list = storService.findByShopIdNoDelete(shopId);
            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, list);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    @ResponseBody
    @RequestMapping(value = "/getStorageByShopId", method = RequestMethod.GET)
    public Map<String, Object> getStorageByShopId(String shopId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 用于返回值的json对象
            Map<String, Object> resultMap = new HashMap<String, Object>();
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null) {
                resultMap.put(JSON_RESULT, FAILED);
                resultMap.put(JSON_MSG, "当前用户失效");
                return resultMap;
            }

            List<StorVO> list = storService.findByShopId(shopId);
            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, list);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 方法简要描述信息.
     * <p>
     * 描述: 删除仓库
     * </p>
     * <p>
     * 备注: 详见顺序图<br>
     * </p>
     */
    @ResponseBody
    @RequestMapping(value = "/deleteStor")
    @SystemControllerLog(module = "仓库管理", operation = "删除仓库", keyCode = "storIds")
    public Map<String, Object> deleteStor(String storIds) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            if (storIds.substring(0, 1).equals(",")) {
                storIds = storIds.substring(1);
            }
            if (storIds.substring(storIds.length() - 1, storIds.length()).equals(",")) {
                storIds = storIds.substring(storIds.length() - 1);
            }
            storService.delete(storIds);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logger.error(ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("storIds", storIds);
        return returnMap;
    }

    /**
     * 方法简要描述信息.
     * <p>
     * 描述: 添加仓库
     * </p>
     * <p>
     * 备注: 详见顺序图<br>
     * </p>
     */
    @ResponseBody
    @RequestMapping(value = "/addStor")
    @SystemControllerLog(module = "仓库管理", operation = "添加仓库", keyCode = "storId")
    public Map<String, Object> addStor(@RequestBody StorVO storVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            StorVO storVO2 = new StorVO();
            storVO2.setStorName(storVO.getStorName());
            List<StorVO> storVOList = storService.getStorByCondition(storVO2);
            if (storVOList.size() >= 1) {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "该仓库名称已存在");
                return returnMap;
            }
            StorVO storVO3 = new StorVO();
            storVO3.setStorCode(storVO.getStorCode());
            List<StorVO> storVOList2 = storService.getStorByCondition(storVO3);
            if (storVOList2.size() >= 1) {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "该仓库编码已存在");
                return returnMap;
            }
            storVO.setDeleted("n");
            storVO.setStorId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));

            // 企业id和企业名称赋值（注：目前2017年7月20日1个人只有1个企业）
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser.getEnterpriseMap() != null && currentUser.getEnterpriseMap().size() > 0) {
                for (Entry<String, String> entry : currentUser.getEnterpriseMap().entrySet()) {
                    storVO.setEntId(entry.getKey());
                    storVO.setEntName(entry.getValue());
                    break;
                }
            }
            storService.insert(storVO);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
            System.out.println(ex);
            System.out.println(returnMap);
        }
        returnMap.put("storId", storVO.getStorId());
        return returnMap;
    }

    /**
     * 方法简要描述信息.
     * <p>
     * 描述: 修改仓库
     * </p>
     * <p>
     * 备注: 详见顺序图<br>
     * </p>
     */
    @ResponseBody
    @RequestMapping(value = "/updateStor")
    @SystemControllerLog(module = "仓库管理", operation = "修改仓库", keyCode = "storId")
    public Map<String, Object> updateStor(@RequestBody StorVO storVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            String updateStorName = storVO.getStorName();
            String storName = storVO.getUpdateStorName();
            if (StringUtils.isNotBlank(updateStorName) && StringUtils.isNotBlank(storName) && !updateStorName.equals(storName)) {
                StorVO storVO2 = new StorVO();
                storVO2.setStorName(updateStorName);
                List<StorVO> storVOList = storService.getStorByCondition(storVO2);
                if (storVOList.size() >= 1) {
                    returnMap.put(JSON_RESULT, FAILED);
                    returnMap.put(JSON_MSG, "该仓库名称已存在");
                    return returnMap;
                }
                String updateStorCode = storVO.getStorCode();
                String storCode = storVO.getUpdateStorCode();
                StorVO storVO3 = new StorVO();
                storVO3.setStorName(updateStorCode);
                List<StorVO> storVOList2 = storService.getStorByCondition(storVO2);
                if (storVOList2.size() >= 1) {
                    returnMap.put(JSON_RESULT, FAILED);
                    returnMap.put(JSON_MSG, "该仓库编码已存在");
                    return returnMap;
                }
            }
            storService.update(storVO);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logger.error(ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("storId", storVO.getStorId());
        return returnMap;
    }
    
    /**
     * 方法简要描述信息.
     * <p>
     * 描述: 修改仓库
     * </p>
     * <p>
     * 备注: 详见顺序图<br>
     * </p>
     */
    @ResponseBody
    @RequestMapping(value = "/updateStorSwitchGJGN")
    @SystemControllerLog(module = "仓库管理", operation = "切换菜鸟仓的国内国际属性", keyCode = "storId")
    public Map<String, Object> updateStorSwitchGJGN(@RequestParam String storId,@RequestParam String cainiaoType) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        StorVO storVO = new StorVO();
        storVO.setStorId(storId);
        try {
            if("gj".equals(cainiaoType)) {
                storVO.setCainiaoType("gn");
            }else {
                storVO.setCainiaoType("gj");
            }
            
            storService.update(storVO);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logger.error(ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("storId", storVO.getStorId());
        return returnMap;
    }

    /**
     * 方法简要描述信息.
     * <p>
     * 描述: 获取仓库详细
     * </p>
     * <p>
     * 备注: 详见顺序图<br>
     * </p>
     */
    @ResponseBody
    @RequestMapping(value = "/getStorDetail", method = RequestMethod.POST)
    public Map<String, Object> getStorDetail(String storId) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            Stor storDetail = storService.selectStorDetail(storId);
            returnMap.put("storDetail", storDetail);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 获取网店下默认仓库
     *
     * @param shopId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = { "/getDefaultStor" })
    public Map<String, Object> getDefaultStor(String shopId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            StorVO shopStor = storService.getDefaultStor(shopId);
            if (shopStor != null) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put("storId", shopStor.getStorId());// 仓库Id
                returnMap.put("storName", shopStor.getStorName());// 仓库名称
                returnMap.put("storCode", shopStor.getStorCode());// 仓库编码
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "获取网店下默认仓库失败");
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        return returnMap;
    }
}
